package com.example.agriapp.presenter;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;

import com.example.agriapp.model.FeedContract;
import com.example.agriapp.model.bean.FeedItem;
import com.example.agriapp.model.FeedModel;
import com.example.agriapp.util.DateUtils;

import java.util.List;
import java.util.UUID;

public class FeedPresenter implements FeedContract.Presenter {
    private FeedContract.View view;
    private FeedModel model;
    
    public FeedPresenter(FeedContract.View view, Context context) {
        this.view = view;
        this.model = new FeedModel(context);
    }
    
    @Override
    public void loadFeeds(int type) {
        view.showLoading();
        new AsyncTask<Void, Void, List<FeedItem>>() {
            @Override
            protected List<FeedItem> doInBackground(Void... voids) {
                if (type==0){
                    return model.getLatestFeeds();
                }else {
                    return model.getFollowedFeeds();
                }

            }
            
            @Override
            protected void onPostExecute(List<FeedItem> feeds) {
                view.hideLoading();
                view.showFeeds(feeds);
            }
        }.execute();
    }
    
    @Override
    public void likeFeed(FeedItem item) {
        model.likeFeed(item.getId());
        item.setLikes(item.getLikes() + 1);
        view.updateFeedItem(item);
    }
    
    @Override
    public void unlikeFeed(FeedItem item) {
        model.unlikeFeed(item.getId());
        item.setLikes(item.getLikes() - 1);
        view.updateFeedItem(item);
    }
    
    @Override
    public void followUser(FeedItem item) {
        model.followUser(item.getUserId());
        item.setFollowed(true);
        view.updateFeedItem(item);
    }
    
    @Override
    public void unfollowUser(FeedItem item) {
        model.unfollowUser(item.getUserId());
        item.setFollowed(false);
        view.updateFeedItem(item);
    }

    @Override
    public void postNewFeed(String content, Uri imageUri) {
        String currentDate = DateUtils.getCurrentDate();
        FeedItem newFeed = new FeedItem(
                UUID.randomUUID().toString(),
                "current_user_id", // 实际项目中应从用户管理模块获取
                "当前用户名",
                "current_avatar",
                content,
                currentDate,
                0, 0, false, false, null,
                imageUri != null ? imageUri.toString() : null
        );

        model.postNewFeed(newFeed);
        view.showPostSuccess();
    }

    @Override
    public void onDestroy() {
        view = null;
    }
}